/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.javanile.elotester;

import java.io.*;
/**
 *
 * @author cicciodarkast
 */
public class EngineInterface extends Thread {
    private String  enginescript;
    private Process process;
    private BufferedReader reader;
    private BufferedWriter writer;

    public EngineInterface(String s) {
        enginescript = s;
    }
    @Override
    public void run() {
        try {
            process = Runtime.getRuntime().exec(enginescript);
            reader  = new BufferedReader(new InputStreamReader(process.getInputStream()));
            writer  = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void exec() {
        this.start();
    }
    public void ferma() {
        try {
            writer.newLine();
            writer.write("quit");
            writer.newLine();
            writer.write("quit");
            writer.newLine();
            writer.write("quit");
            writer.newLine();
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void set(String s) {
        try {
            System.out.println("ss: "+s);
            writer.write(s+"\n");
            
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    public String get() {
        //process.waitFor();
        /*
        String line ;
        while( (  line = reader.readLine() ) != null ) {
            System.out.println(line) ;
        }
         *
         */
        return "";
    }
    public String read() {
        return "";
    }
    public void send(String s) {
        try {
            writer.write(s.trim());
            writer.newLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // TODO code application logic here
        /*
         * Sviluppare un interfacci diretta su un engine classico si usa
         *
            import java.lang.* ;

            public class MyJavaClass {
                public void runCmd(String[] args) {
                    String cmd = "/home_dir/./chess-engine.sh" ;
                    Runtime run = Runtime.getRuntime() ;
                    Process pr = run.exec(cmd) ;
                    pr.waitFor() ;
                    BufferedReader buf = new BufferedReader( new InputStreamReader( pr.getInputStream() ) ) ;
                    while ( ( String line ; line = buf.readLine() ) != null ) {
                        System.out.println(line) ;
                    }
                }
            }
         */
}
